<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '加解密'"
    :close-on-click-modal="false"
    v-loading="loading"
    element-loading-text="正在上传中。。。"
    :visible.sync="visible">
    <el-form :inline="true">
      <el-form-item>
        <el-button @click="handleEnc()">加密</el-button>
        <el-button @click="handleDec()">解密</el-button>
      </el-form-item>
    </el-form>
    <el-input
      type="textarea"
      :rows="4"
      v-model="textarea"
    ></el-input>
    <!--加解密: <textarea ></textarea>-->
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <!--<el-button @click="visible = false">确定</el-button>-->
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        loading: false,
        visible: false,
        downloadUrl: '',
        haspic: false,
        images: [],// 图片存储
        fileContent: '',
        textarea: '',
        dataForm: {
          id: 0,
          path: '',
          createTime: ''
        },
        dataRule: {
          path: [
            { required: true, message: '文件路径不能为空', trigger: 'blur' }
          ],
          createTime: [
            { required: true, message: '创建时间不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (row) {
        this.dataForm.id = row.id || 0
        this.visible = true
        this.$http({
          url: this.$http.adornUrl(`/generator/cryptograph/download`),
          method: 'get',
          params: this.$http.adornParams({
            'id': row.id,
            'path': row.path
          }),
          responseType: 'blob'
        })
          .then(data => {
            if (!data) {
              return
            }
            let url = window.URL.createObjectURL(data.data)
            this.$http({
              url: url,
              method: 'get'
            })
              .then(data => {
                this.textarea = data.data
              })
            /*let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            // 獲取文件名
            let fileName = null
            let filePath = row.path
            if (filePath.indexOf('/') !== -1) {
              fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
            } else {
              fileName = filePath
            }
            // download 屬性定義了下載鏈接的地址而不是跳轉路徑
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()*/
          })
      },
      //加密
      handleEnc() {
        var content = this.fileContent
        this.$http({
          url: this.$http.adornUrl(`/generator/cryptograph/encrypt`),
          method: 'post',
          data: this.$http.adornData(content,false)
        }).then(data => {
          this.textarea = data.data
        })


      },
      handleDec(){
        this.$http({
          url: this.$http.adornUrl(`/generator/cryptograph/decrypt`),
          method: 'get'
        }).then(data => {
          this.textarea = data.data
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/generator/cryptograph/update`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'path': this.dataForm.path,
                'createTime': this.dataForm.createTime
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      submitUpload (id) {
        if (id) {
          this.dataFormSubmit()
        } else {
          if (this.haspic) {
            _.unset(this.dataRule, ["file"])
            this.$refs['dataForm'].validate((valid) => {
              if (valid) {
                this.loading = true
                this.$refs.upload.submit()
              }
            })
          } else {
            // 向rules提价一条对图片的验证。
            _.set(this.dataRule, "file", {required: true, message: "请选择镜像", trigger: "blur"})
            this.$refs['dataForm'].validate(valid => {
              if (valid) {
                console.log("说明文件未上传")
              } else {
                console.log("error submit!!")
                return false
              }
            })
          }
        }
      },
      beforeAvatarUpload (file) {

      },
      imageChange (file, fileList, name) {
        this.images["file"] = fileList;
        this.haspic = true;
        // 如果上传了就不显示提示图片警告
        if (typeof this.images.file != "undefined") {
          if (this.images.file.length > 0) {
            this.$refs["uploadElement"].clearValidate();
          }
        }
      },
      handleRemove (file, fileList) {
        // 如果images为空了说明并没有提交图片所以需要显示警告
        if (typeof this.images.file != "undefined") {
          if (this.images.file.length > 0) {
            this.$refs["uploadElement"].clearValidate();
          } else {
            this.$refs["uploadElement"].validate();
            this.haspic = false;
          }
        }
      },
      handlePreview (file) {
      },
      handleSuccess (res, file, fileList) {
        if (res.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.loading = false
              this.haspic = false
              this.fileList = []
              this.$emit('refreshDataList')
              this.$refs.upload.clearFiles()
            }
          })
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }
    }
  }
</script>
